<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link type="text/css" href="jquery-ui/css/custom-theme/jquery-ui-1.8rc1.custom.css" rel="stylesheet" />	
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="jquery-ui/js/jquery-ui-1.8rc1.custom.min.js"></script> 
<script type="text/javascript" src="filterupdate.js"></script>
<title>AdThwart Options</title>
<style type="text/css" media="screen">
body {
    max-width: 700px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 13px;
}

td {
    font-size: 13px;
    vertical-align: top;
    text-align: left;
}

p {
    margin-top: 0.5em;
}

.rawFilters {
    display: none;
}

.okMsg {
	display: none;
	color: #ffffff;
	background: #30e030;
	font-weight: bold;
	padding: 3px;
}

.errMsg {
	display: none;
	color: #ffffff;
	background: #e03030;
	font-weight:bold;
	padding:3px;
}

/* Filter list entry status message */
.flMsg {
	display: none;
	color: #b0b0b0;
}

</style>
<script type="text/javascript" charset="utf-8">

function loadCheckbox(id) {
	document.getElementById(id).checked = typeof localStorage[id] == "undefined" ? false : localStorage[id] == "true";
}

function saveCheckbox(id) {
    localStorage[id] = document.getElementById(id).checked;
}

// Loads options from localStorage and sets UI elements accordingly
function loadOptions() {
	// Show icon in address bar? True by default
	var shouldShowIcon = localStorage["shouldShowIcon"];
	document.getElementById("shouldShowIcon").checked = typeof shouldShowIcon == "undefined" ? true : shouldShowIcon == "true";

	loadCheckbox("disableInlineTextAds");
	loadCheckbox("specialCaseYouTube");

	// Load user filter URLs
	loadUserFilterURLs();
	for(key in filterFiles) {
		if(!key.match(/^user_/))
			continue;
		addUserURLEntry(key, filterFiles[key]);
	}

	// Filter lists enabled state
	var filterFilesEnabled = typeof localStorage["filterFilesEnabled"] == "string" ? JSON.parse(localStorage["filterFilesEnabled"]) : {"easylist": true };
	for(var key in filterFilesEnabled) {
	    document.getElementById(key).checked = filterFilesEnabled[key];
    }

	// User-entered filters
	var userFilters = localStorage["userFilters"];
	if(typeof userFilters == "undefined")
	    userFilters = JSON.stringify(["qux.us###annoying_AdDiv", "qux.us##.ad_class"]);
	userFilters = JSON.parse(userFilters);
    // Populate list box with filter strings
    for(var i = 0; i < userFilters.length; i++)
        appendToListBox("userFiltersBox", userFilters[i]);
        
    // Excluded domains - sort these alphabetically
    var excludedDomains = localStorage["excludedDomains"];
    if(typeof excludedDomains == "string") {
        excludedDomains = JSON.parse(excludedDomains);
        var buf = [];
        for(var domain in excludedDomains)
            buf.push(domain);
        buf.sort();
        for(var i = 0; i < buf.length; i++)
            appendToListBox("excludedDomainsBox", buf[i]);
    }

	saveOptions(); // Save any defaults that were created
}

// Reads options from UI elements and saves them in localStorage
function saveOptions() {
	saveCheckbox("shouldShowIcon");
	saveCheckbox("disableInlineTextAds");
	saveCheckbox("specialCaseYouTube");
    
    // Filter lists
    var filterFilesEnabled = {};
	var userFilterURLs = {};
	for(var key in filterFiles) {
		filterFilesEnabled[key] = document.getElementById(key).checked;
		if(key.match(/^user_/)) { // User-added filter?
			userFilterURLs[key] = document.getElementById(key + "_url").innerHTML;
		}
	}
	localStorage["filterFilesEnabled"] = JSON.stringify(filterFilesEnabled);
	localStorage["userFilterURLs"] = JSON.stringify(userFilterURLs);

    // Grab contents of userFiltersBox as an array and JSONify it
    var userFiltersBox = document.getElementById("userFiltersBox");
    var userFilters = [];
    for (var i = 0; i < userFiltersBox.length; i++)
        userFilters.push(userFiltersBox.options[i].value);
    localStorage["userFilters"] = JSON.stringify(userFilters);

    // Tell background.html to show/hide icon
    // chrome.extension.sendRequest({reqtype: "refresh-page-icon"});
    // Reload filters
    chrome.extension.sendRequest({reqtype: "reload-filters"});
    
    // Excluded domains
    var excludedDomainsBox = document.getElementById("excludedDomainsBox");
    var excludedDomains = {};
    for (var i = 0; i < excludedDomainsBox.length; i++)
        excludedDomains[excludedDomainsBox.options[i].value] = true;
    localStorage["excludedDomains"] = JSON.stringify(excludedDomains);    
}

// Add a filter string to the list box.
function appendToListBox(boxId, text) {
    var elt = document.createElement("option");
    elt.text = text;
    elt.value = text;
    document.getElementById(boxId).add(elt, null);
}

function addWhitelistDomain() {
    var domain = document.getElementById("newWhitelistDomain").value.split(' ').join('');
    appendToListBox("excludedDomainsBox", domain);
    saveOptions();
}

// Adds filter text that user typed to the selection box
function addTypedFilter() {
    var filterText = document.getElementById("newFilter").value.split(' ').join('');
    // ABP filters don't have whitespace
    if(filterText == "") return;
    appendToListBox("userFiltersBox", filterText);
    saveOptions();
}

// Removes currently selected whitelisted domains
function removeSelectedExcludedDomain() {
    var excludedDomainsBox = document.getElementById("excludedDomainsBox");
    for (var i = excludedDomainsBox.length-1; i >= 0; i--) {
        if (excludedDomainsBox.options[i].selected)
            excludedDomainsBox.remove(i);
    }
    saveOptions();
}

// Removes all currently selected filters
function removeSelectedFilters() {
    var userFiltersBox = document.getElementById("userFiltersBox");
    for (var i = userFiltersBox.length-1; i >= 0; i--) {
        if (userFiltersBox.options[i].selected)
            userFiltersBox.remove(i);
    }
    saveOptions();
}

// Shows raw filters box and fills it with the current user filters
function showFiltersInRawFormat() {
    $(".rawFilters").show();
	var userFilters = localStorage["userFilters"];
    if(typeof userFilters != "undefined") {
    	userFilters = JSON.parse(userFilters);
        document.getElementById("rawFiltersText").value = userFilters.join("\n");
    }
}

// Imports filters in the raw text box
function importRawFiltersText() {
    $("#userFiltersBox").children().remove();
    var filters = document.getElementById("rawFiltersText").value.split("\n");
    for(var i = 0; i < filters.length; i++) {
        var text = filters[i].replace(/\s+$/, "").replace(/^\s+/, "");
        if(text.length > 0) {
			// Filter out "comment" characters
			switch(text[0]) {
				case '(': 
				case '[':
				case '!':
					break;
				default:
	            	appendToListBox("userFiltersBox", text);
			}
		}
    }
	saveOptions();
}

// Called when user explicitly requests filter list updates
function updateFilterLists() {
	for(key in filterFiles) {
		// Hide status message
		$("#" + key + "_msg").css("display", "none");
		updateFilterList(key);
	}
}


// Provides a more readable string of the current date and time
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
function saneDateString(when) {
	var d = new Date(when);
	var h = d.getHours();
	var ampm = "am";
	if(h > 12) {
		h -= 12;
		ampm = "pm";
	}
	if(h == 0)
		h = 12;
	var m = d.getMinutes();
	if(m < 10)
		m = "0" + m;
	var timeString = h + ":" + m + " " + ampm;
	var now = new Date();
	if(d.getDate() == now.getDate() && d.getMonth() == now.getMonth() && d.getFullYear() == now.getFullYear())
		dateString = " today";
	else
		dateString = " on " + d.getDate() + " " + monthNames[d.getMonth()] + " " + d.getFullYear();

	return(timeString + dateString);
}

// Updates a single filter list and informs the user what happened
function updateFilterList(key) {
	// Checkbox not checked? Not a URL?
	if(document.getElementById(key).checked == false || !filterFiles[key].match(/^http/))
		return;

	// Hide status message
	$("#" + key + "_msg").css("display", "none");

    new FilterListFetcher(key, function(fetcher) {
		if(fetcher.error) {
			$("#" + fetcher.name + "_msg").text(fetcher.error).css("color", "#a03030").css("display", "inline");
			document.getElementById(key).checked = false;
		} else {
			$("#" + fetcher.name + "_msg").css("color", "#b0b0b0").text("Updated just now").css("display", "inline");
		}
    });
}

// Checks into our possible cached copy of this filter list and updates the UI accordingly
function checkFilterList(key) {
	// Hide status message
	$("#" + key + "_msg").css("display", "none");

	var url = filterFiles[key];
	if(url in localStorage) {
		var list = JSON.parse(localStorage[url]);
		if(!list.error) {
		    // We didn't used to store lastDownloaded, so we check for its existence and fall back on lastUpdated if necessary
		    // lastDownloaded: Last time the list was downloaded
		    // lastUpdated: Last time the list reports that it was updated, or else the last time it was downloaded
		    var lastDownloaded = list.lastDownloaded ? list.lastDownloaded : list.lastUpdated;
			$("#" + key + "_msg").css("color", "#b0b0b0").text("Last updated at " + saneDateString(lastDownloaded)).css("display", "inline");
		}
		else {
			// Display error only if checked
			if(document.getElementById(key).checked) {
				$("#" + key + "_msg").text(list.error).css("color", "#a03030").css("display", "inline");
			}
		}
	} else {
		// If we don't have this filter list but it's enabled, fetch it
		if(document.getElementById(key).checked == true)
			updateFilterList(key);
	}
}

// Check to see if all filter lists are up to date
function checkAllFilterLists() {
	for(key in filterFiles) {
		checkFilterList(key);
	}
}

// Deletes an entry for a filter list URL from the UI
function deleteUserURLEntry(key) {
	if(key in filterFiles)
		delete filterFiles[key];
	var foo = document.getElementById(key + "_div");
	document.getElementById("userFilterLists").removeChild(foo);
	saveOptions();
}

// Adds an entry for a filter list URL to the UI
function addUserURLEntry(key, url) {
	var checkbox = document.createElement('input');
	checkbox.type = "checkbox";
	checkbox.id = key;
	checkbox.checked = true;
	checkbox.addEventListener("click", function() { checkFilterList(key); saveOptions(); });
	var label = document.createElement('span');
	label.id = key + "_url";
	label.innerHTML = url;
	var del = document.createElement('span');
	del.innerHTML = ' <a href="#" onClick="deleteUserURLEntry(\'' + key + '\')">[delete]</a> ';
	// Status message
	var msg = document.createElement("span");
	msg.id = key + "_msg";
	msg.class = "flMsg";
	var div = document.createElement('div');
	div.id = key + "_div";
	div.appendChild(checkbox);
	div.appendChild(label);
	div.appendChild(del);
	div.appendChild(msg);
	document.getElementById("userFilterLists").appendChild(div);

}

function addUserURLFromBox() {
	var key = "user_" + (new Date()).getTime();
	var url = document.getElementById("newURL").value;

	// Extract URL from ABP subscription link
	var matches;
	if(matches = url.match(/^abp:subscribe.*[\?&]location=(.+?)(&|$)/i))
		url = decodeURIComponent(matches[1]);

	if(!url.match(/^http/) && !url.match(/^file/))
		return;
	addUserURLEntry(key, url);
	document.getElementById("newURL").value = "";
	filterFiles[key] = url;
	// Trigger download
	updateFilterList(key);
	saveOptions();
}

$(function() { 
    $('#tabs').tabs(); 
    $('button').button(); 
    $('.refreshButton').button('option', 'icons', {primary: 'ui-icon-refresh'});
    $('.addButton').button('option', 'icons', {primary: 'ui-icon-plus'});
    $('.removeButton').button('option', 'icons', {primary: 'ui-icon-minus'});
});
</script>
</head>
<body onload="loadOptions(); checkAllFilterLists()">
<table><tr><td style="padding-right: 8px"><img src="icons/face-devilish-32.png"></td><td><h1>AdThwart Options</h1></td></tr></table>

<div id="tabs"><ul>
<li><a href="#tab-filterlists">Filter lists</a></li>
<li><a href="#tab-userfilters">Add your own filters</a></li>
<li><a href="#tab-whitelisted">Whitelisted domains</a></li>
<li><a href="#tab-general">General</a></li>
</ul>

<div id="tab-filterlists">
<p>Enable only the filter lists you need &mdash; too many can make Chrome unresponsive.</p>
<p>Out-of-date lists are updated periodically. Or, you can <button class="refreshButton" onclick="updateFilterLists()">Update now.</button><br/>
<br/>
<input type="checkbox" id="easylist" onClick="checkFilterList('easylist'); saveOptions()" /><a href="http://easylist.adblockplus.org/">EasyList</a> by Ares2 and Rick752 <span id="easylist_msg" class="flMsg"></span><br/>

<input type="checkbox" id="germany" onClick="checkFilterList('germany'); saveOptions()" />EasyList Germany by Ares2 <span id="germany_msg" class="flMsg"></span><br/>

<input type="checkbox" id="fanboy_es" onClick="checkFilterList('fanboy_es'); saveOptions()" />Fanboy's Español/Português supplement <span id="fanboy_es_msg" class="flMsg"></span><br/>

<input type="checkbox" id="france" onClick="checkFilterList('france'); saveOptions()" />EasyList + Liste FR (Français) by Lian <span id="france_msg" class="flMsg"></span><br/>

<input type="checkbox" id="china" onClick="checkFilterList('china'); saveOptions()" /><a href="http://code.google.com/p/adblock-chinalist/">ChinaList</a> (汉语) by Gythialy <span id="china_msg" class="flMsg"></span><br/>

<input type="checkbox" id="russia" onClick= "checkFilterList('russia'); saveOptions()" /><a href="http://code.google.com/p/ruadlist/">RuAdList</a> (Русский, Українська) <span id="russia_msg" class="flMsg"></span><br/>

<input type="checkbox" id="korea" onClick="checkFilterList('korea'); saveOptions()" /><a href="http://corset.47.forumer.com/">Corset</a> (한국말) by maybee <span id="korea_msg" class="flMsg"></span><br/>

<input type="checkbox" id="romania" onClick="checkFilterList('romania'); saveOptions()" /><a href="http://www.picpoc.ro/">ROList</a> (Românesc) by MenetZ <span id="romania_msg" class="flMsg"></span><br/>

<input type="checkbox" id="italy" onClick="checkFilterList('italy'); saveOptions()" /><a href="http://gfsolone.com/realizzazioni/altro/abp-x-files">Xfiles</a> (Italiano) by Gioxx <span id="italy_msg" class="flMsg"></span><br/>

<input type="checkbox" id="vietnam" onClick="checkFilterList('vietnam'); saveOptions()" />Việt Nam list by NGUYỄN Mạnh Hùng <span id="vietnam_msg" class="flMsg"></span><br/>

<input type="checkbox" id="poland" onClick="checkFilterList('poland'); saveOptions()" />PLgeneral (Polski) by Krzysztof Niecko 
<span id="poland_msg" class="flMsg"></span><br/>

<input type="checkbox" id="extras" onClick="checkFilterList('extras'); saveOptions()" /><a href="http://adthwart.appspot.com/filters?n=extras">AdThwart extra filters</a> <span id="extras_msg" class="flMsg"></span><br/>

<div id="userFilterLists" style="margin-bottom: 8px"></div>

<div id="addURLField">
Add a Firefox AdBlock Plus <a href="http://adblockplus.org/en/subscriptions">filter list</a>:<br/>
<input type="text" value="" id="newURL" style="width:400px">
<button class="addButton" onClick="addUserURLFromBox()">Add URL</button><br/>
</div>
</div>

<div id="tab-whitelisted">
<p>AdThwart is disabled for the domains listed below. You can add a domain either via the AdThwart icon in
the address bar or by typing the domain (not a URL) in the box and clicking the "Add domain" button.</p>

<table>
<tr><td>
<input type="text" value="" id="newWhitelistDomain" style="width:400px"></td>
<td><button class="addButton" onClick="addWhitelistDomain()">Add domain</button></td></tr>

<tr><td>
<select id="excludedDomainsBox" size="10" style="width:400px; background: white;">
</select></td><td>
<button class="removeButton" onClick="removeSelectedExcludedDomain()">Remove selected</button>
</td></tr></table>
</div>
<div id="tab-userfilters">
<p>Your filter must follow the <a href="http://adblockplus.org/en/filters">AdBlock Plus filter syntax</a>. Certain filter types, like object-subrequest, are not supported.</p>

<table>
<tr><td>
<input type="text" value="" id="newFilter" style="width:500px"></td>
<td><button class="addButton" onClick="addTypedFilter()">Add</button></td></tr>
<tr><td>
<select id="userFiltersBox" size="20" style="width: 500px; background: white;">
</select>
</td><td>
<button class="removeButton" onClick="removeSelectedFilters()">Remove selected</button></td></tr>

<tr><td>
<div style="font-size: 90%; text-align: right"><a onClick="showFiltersInRawFormat()" href="#">Edit filters as raw text</a></div>
</td></tr>
<tr><td>
<div class="rawFilters" style="width: 500px">
<textarea id="rawFiltersText" style="width: 100%; height: 300px"></textarea>   
</div></td>
<td><div class="rawFilters"><button onClick="importRawFiltersText()">Apply changes</button></div></td>
</tr></table>

</div>

<div id="tab-general">
<input type="checkbox" id="shouldShowIcon" onClick="saveOptions()" /> Show icon in address bar<br/>
<input type="checkbox" id="disableInlineTextAds" onClick="saveOptions()" /> <a href="http://userscripts.org/scripts/show/3637">Disable inline text ads</a><br/>
<input type="checkbox" id="specialCaseYouTube" onClick="saveOptions()" /> Block ads inside YouTube videos (does not work with the FlashBlock extension)<br/>

<br/>
Found a bug in AdThwart? Please <a href="http://code.google.com/p/adthwart/issues/entry">report it here</a>.

</div>
</div>

</body>
</html>
